<template>
    <!-- 待对异常 -->
    <div class="await">
        <SearchBar
            class="form"
            @onSearch="handleSearch"
            @childFn="resetSeeelementForm"
        >
            <SearchBarItem label="子订单号：" :labelLg="8">
                <Input
                    type="text"
                    v-model="searchSettlementModule.subOrderId"
                    placeholder="请输入"
                    clearable
                />
            </SearchBarItem>
            <SearchBarItem label="主订单号：" :labelLg="8">
                <Input
                    type="text"
                    v-model="searchSettlementModule.orderId"
                    placeholder="请输入"
                    clearable
                />
            </SearchBarItem>
            <SearchBarItem label="商户名称：" :labelLg="8">
                <Input
                    type="text"
                    v-model="searchSettlementModule.merchantName"
                    placeholder="请输入"
                    clearable
                />
            </SearchBarItem>
            <SearchBarItem label="规则编码：" :labelLg="8">
                <Input
                    type="text"
                    v-model="searchSettlementModule.clearRuleCode"
                    placeholder="请输入"
                    clearable
                />
            </SearchBarItem>
            <SearchBarItem label="商品类型：" :labelLg="8">
                <Select
                    v-model="searchSettlementModule.orderSource"
                    placeholder="请选择"
                    :clearable="isClear"
                >
                    <Option
                        :value="item.key"
                        v-for="(item, key) in selectSource"
                        :key="key"
                        >{{ item.value }}</Option
                    >
                </Select>
            </SearchBarItem>
            <SearchBarItem label="交易时间：" :labelLg="8">
                <DatePicker
                    type="daterange"
                    class="timeWidth"
                    ref="createSettlementDatePicker1"
                    :value="searchSettlementModule.dataTime"
                    split-panels
                    transfer
                    placeholder="请选择日期区间"
                    @on-change="searchTime"
                ></DatePicker>
            </SearchBarItem>
            <SearchBarItem label="核销时间：" :labelLg="8">
                <DatePicker
                    type="daterange"
                    class="timeWidth"
                    ref="createSettlementDatePicker2"
                    :value="searchSettlementModule.verificationTime"
                    split-panels
                    transfer
                    placeholder="请选择日期区间"
                    @on-change="searchVerificationTime"
                ></DatePicker>
            </SearchBarItem>
        </SearchBar>
        <RemoteTable
            :namespace="namespace"
            :columns="columns"
            :showPageInfo="false"
            @onSortChange="onSortChange"
            :isFixedHeader="true"
            :selected="batchData"
            @onSelectionChange="getListChecked"
            ref="tableData"
        >
          <template #extra>
            <Authc permissions="trade:settlement:unReconciled">
              <Button type="primary" @click="exportExcel">导出</Button>
            </Authc>
            <Authc permissions="trade:settlement:unReconciled">
              <Button type="primary" @click="exportExcelAll">全部导出</Button>
            </Authc>
            <Authc permissions="trade:settlement:unReconciled">
              <Button type="primary" @click="batchProces">批量处理</Button>
            </Authc>
          </template>

        </RemoteTable>
        <div class="loadMoreBtn">
            <Button
                type="primary"
                @click="loadMore"
                :disabled="isDisabledloadBtn"
                >加载更多</Button
            >
        </div>
    </div>
</template>
<script>
import {
    Button,
    Input,
    Modal,
    Message,
    Col,
    Row,
    Form,
    FormItem,
    DatePicker,
    Select,
    Option,
    Card,
    Tabs,
    TabPane
} from "view-design";
import RemoteTable from "@/components/RemoteTable";
import SearchBar from "@/components/SearchBar";
import RemoteSelect from "@/components/RemoteSelect";
import { namespace } from "../../Module/awaitBillClearingModule";
import Authc from "@/components/Authc";
import Tables from "@/components/tables";
import Action from "./Action";
import config from "@/utils/config";
import util from '@/utils/util';
import appService from "@/utils/appService";

export default {
    name: "clearingAbnormal",
    components: {
        RemoteTable,
        SearchBar,
        SearchBarItem: SearchBar.SearchBarItem,
        RemoteSelect,
        Authc,
        Action,
        Tables,
        Button,
        Input,
        Modal,
        Message,
        Col,
        Row,
        Form,
        FormItem,
        DatePicker,
        Select,
        Option,
        Card,
        Tabs,
        TabPane
    },
    props: {
        isDetailsPageReturn: Boolean,
        selectSource: Array
    },
    data() {
        return {
            namespace: namespace,
            isDisabledloadBtn: false /** 控制加载更多按钮 **/,
            currentPage: 1 /** 用来控制加载更新 **/,
            batchData: [] /** 多选选中 */,
            isClear: true,
            loading: true,
            searchSettlementModule: [],
            // selectSourceList: this.selectSource, /** 商品类型 */
            columns: [
                {
                    type: "selection",
                    align: "center",
                    // fixed: "left",
                    minWidth: 55
                },
                {
                    title: "序号",
                    type: "index",
                    align: "center",
                    // fixed: "left",
                    minWidth: 80
                },
                {
                    title: "子订单号",
                    key: "subOrderId",
                    align: "center",
                    // fixed: "left",
                    minWidth: 180
                },
                {
                    title: "主订单号",
                    key: "orderId",
                    align: "center",
                    minWidth: 180
                },
                {
                    title: "商品名称",
                    key: "productName",
                    align: "center",
                    minWidth: 210
                },
                {
                    title: "商品编码",
                    key: "productCode",
                    align: "center",
                    minWidth: 280
                },
                {
                    title: "商品类型",
                    key: "orderSourceCn",
                    align: "center",
                    minWidth: 100
                },
                {
                    title: "商户名称",
                    key: "merchantName",
                    align: "center",
                    minWidth: 210
                },
                {
                    title: "商户编码",
                    key: "merchantCode",
                    align: "center",
                    minWidth: 280
                },
                {
                    title: "清分渠道",
                    key: "payChannelCodeCn",
                    align: "center",
                    minWidth: 100
                },
                {
                    title: "清分金额(元)",
                    key: "verifiedAmount",
                    align: "center",
                    minWidth: 120,
                    render: (h, params) => {
                        let item = params.row.verifiedAmount / 100;
                        return h("span", util.toMoney(item));
                    }
                },
                {
                    title: "规则编码",
                    key: "clearRuleCode",
                    align: "center",
                    minWidth: 220
                },
                {
                    title: "交易时间",
                    key: "payTime",
                    align: "center",
                    minWidth: 150
                },
                {
                    title: "核销时间",
                    key: "verifiedTime",
                    align: "center",
                    minWidth: 150
                },
                {
                    title: "清分周期",
                    key: "clearingCycleMode",
                    align: "center",
                    minWidth: 150,
                    render: (h, params) => {
                        switch (params.row.clearingCycleMode) {
                            case '1':
                                return h('span', `T + ${params.row.clearingCycleValue}`);
                                break;
                            case '2':
                                return h('span', `${params.row.clearingCycleValueExt}日/${params.row.clearingCycleValue}个月`);
                                break;
                        }
                    }
                },
                {
                    title: "操作",
                    key: "action",
                    align: "center",
                    // fixed: "right",
                    permissions: ["trade:settlement:unReconciled"],
                    minWidth: 150,
                    render: function(h, data) {
                        return h(Action, {
                            props: {
                                row: data.row
                            }
                        });
                    }
                }
            ]
        };
    },
    created() {
        console.log(this.$store.state[namespace], 'data')
        /** 是否从详情页面返回 **/
        if( this.isDetailsPageReturn ) {
            this.setDataModule();
        } else {
            this.$store.commit(`${namespace}/reviseQuery`);
        }
    },
    methods: {
        // 交易时间
        searchTime(date, type) {
            this.searchSettlementModule.payTimeBegin = date ? date[0] : "";
            this.searchSettlementModule.payTimeEnd = date ? date[1] : "";
        },
        // 核销时间
        searchVerificationTime(date, type) {
            this.searchSettlementModule.verifiedTimeBegin = date
                ? date[0]
                : "";
            this.searchSettlementModule.verifiedTimeEnd = date ? date[1] : "";
        },

        handleSearch() {
            let page = {
                currentPage: 1,
                pageSize: 50,
                isException: '1'
            };
            this.$store.dispatch(`${namespace}/query`, {
                ...this.searchSettlementModule,
                ...page
            });
        },
        /** 列表选择 **/
        getListChecked(data) {
            console.log(data, 'data')
            this.batchData = data;
        },
        /** 批量处理 */
        batchProces() {
            this.$router.push({ path: "AwaitBillBatchProces", query: {} });
        },
        exportExcelAll () {
            let dataList = this.$store.state[namespace].pageInfo.list;
            if (dataList.length) {
                let tables = this.$refs.tableData.getTables();
                tables.exportCsv({
                    filename: "待对账单异常全部导出",
                    original: false,
                    columns: this.columns.filter(
                        (col, index) =>
                            index > 1 && index < this.columns.length - 1
                    ),
                    data: dataList.map(
                        ({
                            subOrderId,
                            orderId,
                            productName,
                            productCode,
                            orderSourceCn,
                            merchantName,
                            merchantCode,
                            payChannelCodeCn,
                            verifiedAmount,
                            clearRuleCode,
                            payTime,
                            verifiedTime,
                            shouldClearDate,
                            clearingCycleMode,
                            clearingCycleValueExt,
                            clearingCycleValue
                        }) => {
                            return {
                                subOrderId: subOrderId ? "\t" + subOrderId : "",
                                orderId: orderId ? "\t" + orderId : "",
                                productName: productName ? productName : "",
                                productCode: productCode ? "\t" + productCode : "",
                                orderSourceCn: orderSourceCn ? orderSourceCn : "",
                                merchantName: merchantName ? merchantName : "",
                                merchantCode: merchantCode ? "\t" + merchantCode : "",
                                payChannelCodeCn: payChannelCodeCn ? payChannelCodeCn : "",
                                verifiedAmount: verifiedAmount ? "\t" + verifiedAmount / 100 : `0`,
                                clearRuleCode: clearRuleCode ? "\t" + clearRuleCode : "",
                                payTime: payTime ? "\t" + payTime : "",
                                verifiedTime: verifiedTime ? "\t" + verifiedTime : "",
                                shouldClearDate: shouldClearDate ? "\t" + shouldClearDate : "",
                                clearingCycleMode: clearingCycleMode == 1 ? '\t' + `T + ${clearingCycleValue}` : clearingCycleMode == 2 ?  '\t' + `${clearingCycleValueExt}日/${clearingCycleValue}个月`: '',
                            };
                        }
                    )
                });
            }
        },
        /** 本地导出 */
        exportExcel() {
            if (this.batchData.length) {
                let tables = this.$refs.tableData.getTables();
                tables.exportCsv({
                    filename: "待对账单异常",
                    original: false,
                    columns: this.columns.filter(
                        (col, index) =>
                            index > 1 && index < this.columns.length - 1
                    ),
                    data: this.batchData.map(
                        ({
                            subOrderId,
                            orderId,
                            productName,
                            productCode,
                            orderSourceCn,
                            merchantName,
                            merchantCode,
                            payChannelCodeCn,
                            verifiedAmount,
                            clearRuleCode,
                            payTime,
                            verifiedTime,
                            shouldClearDate,
                            clearingCycleMode,
                            clearingCycleValueExt,
                            clearingCycleValue
                        }) => {
                            return {
                                subOrderId: subOrderId ? "\t" + subOrderId : "",
                                orderId: orderId ? "\t" + orderId : "",
                                productName: productName ? productName : "",
                                productCode: productCode ? "\t" + productCode : "",
                                orderSourceCn: orderSourceCn ? orderSourceCn : "",
                                merchantName: merchantName ? merchantName : "",
                                merchantCode: merchantCode ? "\t" + merchantCode : "",
                                payChannelCodeCn: payChannelCodeCn ? payChannelCodeCn : "",
                                verifiedAmount: verifiedAmount ? "\t" + verifiedAmount / 100 : "0",
                                clearRuleCode: clearRuleCode ? "\t" + clearRuleCode : "",
                                payTime: payTime ? "\t" + payTime : "",
                                verifiedTime: verifiedTime ? "\t" + verifiedTime : "",
                                shouldClearDate: shouldClearDate ? "\t" + shouldClearDate : "",
                                clearingCycleMode: clearingCycleMode == 1 ? '\t' + `T + ${clearingCycleValue}` : clearingCycleMode == 2 ?  '\t' + `${clearingCycleValueExt}日/${clearingCycleValue}个月`: ''
                            };
                        }
                    )
                });
            } else {
                this.$Message.warning("请勾选");
            }
        },
        onSortChange(sort) {
            if (sort.order === "normal") {
                this.queryParam.order = [];
            } else {
                this.queryParam.order = [sort.key + " " + sort.order];
            }
            this.handleSearch();
        },
        // 清空异常单事件
        resetSeeelementForm() {
            this.$set(this.searchSettlementModule, "subOrderId", "");
            this.$set(this.searchSettlementModule, "orderId", "");
            this.$set(this.searchSettlementModule, "merchantName", "");
            this.$set(this.searchSettlementModule, "clearRuleCode", "");
            this.$set(this.searchSettlementModule, "orderSource", "");
            // 清空时间选择;
            this.$refs["createSettlementDatePicker1"].handleClear();
            this.$refs["createSettlementDatePicker2"].handleClear();
        },
        /** 加载更多 **/
        async loadMore() {
            try {
                let dataList = this.$store.state[namespace].pageInfo.list;
                console.log(dataList, 'data')
                // for (let i = 0; i < dataList.length; i++) {
                //     dataList[i]._checked = false;
                //     for (let j = 0; j < this.batchData.length; j++) {
                //         if (this.batchData[j].id == dataList[i].id) {
                //             dataList[i]._checked = true;
                //         }
                //     }
                // }
                this.isDisabledloadBtn = true; // 每次请求都禁止按钮点击
                let obj = {
                    currentPage: ++this.currentPage,
                    pageSize: 50,
                    isException: '1'
                };
                let res = await this.$store.dispatch(
                    `${namespace}/getMoreList`,
                    { ...this.searchSettlementModule, ...obj }
                );

                let listData = res.data.data.list;
                if (listData.length != 0) {
                    this.$store.commit(`${namespace}/pushDataToList`, listData);
                } else {
                    --this.currentPage;
                    this.$Message.info({
                        content: "没有更多数据了！"
                    });
                }
                this.isDisabledloadBtn = false;
            } catch (error) {
                this.$Message.error({
                    content: error
                });
            }
        },
        /** 返回的时候设置下搜索参数 **/
        setDataModule(){
            for(const key in this.$store.state[`${namespace}`].query) {
                if ( key != 'currentPage' && key != 'pageSize' && key != 'isException') {
                    this.searchSettlementModule[key] = this.$store.state[`${namespace}`].query[key];
                }
            }
        }
    },
    async mounted() {
        setTimeout(() => {
            this.loading = false;
        }, 1000);
    }
};
</script>

<style lang="less" scoped>
.await {
    .timeWidth {
        width: 100%;
    }
    .loadMoreBtn {
        margin-top: 20px;
        text-align: center;
    }
}
</style>
